package com.hslxy.malllearning.service.impl;

import com.hslxy.malllearning.common.api.CommonResult;
import com.hslxy.malllearning.service.RedisService;
import com.hslxy.malllearning.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.authcode}")
    private String REDIS_KEY_PREFIX_AUTHCODE;

    @Value("${redis.key.expire.authcode}")
    private Long REDIS_KEY_EXPIRE_AUTHCODE;

    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 6; i++){
            sb.append(random.nextInt(10));
        }
        redisService.set(REDIS_KEY_PREFIX_AUTHCODE + telephone, sb.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTHCODE +telephone, REDIS_KEY_EXPIRE_AUTHCODE);
        return CommonResult.success(sb.toString(), "验证码获取成功");
    }

    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isEmpty(authCode)){
            return CommonResult.failed("请输入验证码");
        }
        String s = redisService.get(REDIS_KEY_PREFIX_AUTHCODE + telephone);
        if (authCode.equals(s)){
            return CommonResult.success(null, "验证成功");
        }else {
            return CommonResult.failed("验证失败");
        }
    }
}
